<?php

class AdminhtmlARB extends CActiveRecordBehavior
{
	
	//only catch original data on update event.
	/*
	public function beforeSave($event)
	{
		$model= $event->sender;
		if ( !$model->getIsNewRecord() ) {
			Yii::app()->admin->setFlash($model->tableName(). '_Orig_Attribute', $model->attributes );
		}
	}
	*/
	
	public function afterSave($event)
	{
		$model= $event->sender;
		$logModel = new AdminhtmlLog();
		if ( !$model->getIsNewRecord() ) {
			if ( Yii::app()->admin->hasFlash($model->tableName(). '_Orig_Attribute') ) {
				$origData= Yii::app()->admin->getFlash($model->tableName(). '_Orig_Attribute');
				$newData= $model->attributes;
				$actionInfo = $insert = $modify = '';
				foreach ($newData as $k=> $v) {
					if ( !isset($origData[$k]) ) {
	
						$insert .= "{$model->getAttributeLabel($k)},";
					} elseif ($newData[$k]!= $origData[$k]) {
						
						$modify .= "{$model->getAttributeLabel($k)},";
					}
				}
				//print_r($origData);print_r($newData);die;
				$actionInfo .= $insert? '补充:"'. $insert: '"';
				$actionInfo .= $modify? '修改:"'. $modify: '"';
				
			} else {
				$actionInfo = '更新数据ID#'. $model->getPrimaryKey();
				
			}
			$logModel->actionRecord(AdminhtmlLog::ACTION_TYPE_UPDATE, array(
				'action_info'=> $actionInfo,
				'action_model'=> $model->getResourceName(),
			) );
			
		} else {
			$actionInfo = '新增数据ID#'. $model->getPrimaryKey();
			$logModel->actionRecord(AdminhtmlLog::ACTION_TYPE_CREATE, array(
				'action_info'=> $actionInfo,
				'action_model'=> $model->getResourceName(),
			) );
		}
	}
	
	public function afterDelete($event)
	{
		$model= $event->sender;
		$logModel = new AdminhtmlLog();
		$actionInfo = '删除数据ID#'. $model->getPrimaryKey();
		$logModel->actionRecord(AdminhtmlLog::ACTION_TYPE_DELETE, array(
			'action_info'=> $actionInfo,
			'action_model'=> $model->getResourceName(),
		) );
	}
	
}
